package com.inspectortime.webapp;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.inspectortime.domain.Inspector;
import com.inspectortime.domain.type.State;
import com.inspectortime.mail.service.AbstractMailMessage;
import com.inspectortime.mail.service.EmailDeliveryException;
import com.inspectortime.mail.service.MailService;
import com.inspectortime.mail.service.StaticMailMessage;
import com.inspectortime.mail.service.StaticMailMessageTemplateNames;
import com.inspectortime.repository.Factory;
import com.inspectortime.repository.Repository;
import com.inspectortime.util.SpringValidatorUtils;
import com.inspectortime.webapp.util.CustomStateEditor;
import com.inspectortime.webapp.util.HttpSessionUtils;

/**
 * @author mkvalsvik
 *
 */
public class RegisterController extends SimpleFormController {
	
	private static Log log = LogFactory.getLog(RegisterController.class);
	
	private static String PICK_INSPECTOR_CONTROLLER = "schedule1.html";

	private Repository repository;
	private Factory factory;
	private String defaultTemplateSourcePath;
	private String newTemplateParentPath;
	private MailService mailService;

	
	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
		binder.registerCustomEditor(State.class, new CustomStateEditor());
	}
	
	protected Map referenceData(HttpServletRequest request) throws Exception {
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("states", State.values());
		return data;
	}
	
	/**
	 * Verify that the user-entered company doesn't already exist. 
	 */
	protected void onBindAndValidate(HttpServletRequest request, Object command, BindException errors) throws Exception {
		SpringValidatorUtils.logValidationErrors(log, errors);
	}

	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		Inspector inspector = factory.createInspector();
		
		// Set default fee
		inspector.getCompany().setBaseInspectionFee(400);
		return inspector;
	}

	protected ModelAndView onSubmit(HttpServletRequest request,	HttpServletResponse response, Object command, BindException errors)
			throws Exception {

		Inspector inspector = (Inspector) command;		
		
		// Save
		inspector.setCleartextPassword(inspector.getPassword());
		inspector.save();

		// Stick user in session
		HttpSessionUtils.storeLoggedInUser(request, inspector);
		log.info("New user registered: " + inspector.getEmail());
		
		// send welcome email to inspector
		Map<String, Object> props = new HashMap<String, Object>();
		props.put("inspector", inspector);
		props.put("availabilityUrl", getAvailabilityLink(request, inspector));
		String toEmail = inspector.getEmail();
		String subject = "Welcome to Inspector Time";
		AbstractMailMessage message = new StaticMailMessage(StaticMailMessageTemplateNames.WELCOME_NEW_REGISTRATION, props, toEmail, subject);
		try {
			this.mailService.send(message);
		} catch(EmailDeliveryException e) {
			//Let's eat this exception instead of throwing an error page at the user
			log.error(e);
		}

		// render success view
		if (getSuccessView() == null) {
			throw new ServletException("successView isn't set");
		}
		
		
		return new ModelAndView(getSuccessView(), errors.getModel());
	}
	
	private String getAvailabilityLink(HttpServletRequest request, Inspector inspector) {
		String requestedUrl = request.getRequestURL().toString();
		String baseUrl = requestedUrl.substring(0, requestedUrl.lastIndexOf("/"));
		return baseUrl + "/inspectors/" + inspector.getCompany().getShortName() + "/" + PICK_INSPECTOR_CONTROLLER;
	}
	
	public void setDefaultTemplateSourcePath(String defaultTemplateSourcePath) {
		this.defaultTemplateSourcePath = defaultTemplateSourcePath;
	}

	public void setNewTemplateParentPath(String newTemplateParentPath) {
		this.newTemplateParentPath = newTemplateParentPath;
	}

	public void setRepository(Repository repository) {
		this.repository = repository;
	}
	
	public void setFactory(Factory factory) {
		this.factory = factory;
	}	

	public void setMailService(MailService mailService) {
		this.mailService = mailService;
	}
	
	
}
